<template>
  <div>
    <!-- 1. nav-bar -->
    <van-nav-bar title="黑马头条" />
    <!-- 2. 表单登录 -->
    <van-form @failed="onFailed" @submit="onSubmit">
      <van-field
        v-model.trim="user.mobile"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[{ pattern: /^1\d{10}$/, mobile: '请输入正确的手机号' }]"
      />
      <van-field
        v-model.trim="user.code"
        type="password"
        name="验证码"
        label="验证码"
        placeholder="验证码"
        :rules="[{ pattern: /^\d{6}$/, mobile: '请输入六位验证码' }]"
      />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>

export default {
  name: 'login',

  data () {
    return {
      user: {
        mobile: '13812121212', // 测试账号可以登录
        code: '246810'
      }
    }
  },

  methods: {
    async doLogin () {
      this.$toast({
        duration: 0, // 持续展示 toast,永远不会关闭，它会被后续的toast覆盖
        overlay: true, // 整体添加一个遮罩
        message: '加载中...'
      })
      // 发请求
      try {
        // await getProfile()
        // 获取token，并保存到vuex中
        await this.$store.dispatch('userLogin', this.user)

        // 调用带命名空间的moudules中的action
        await this.$store.dispatch('user/getProfile')
        this.$toast.success('登录成功')

        // 跳转页面到主页
        this.$router.push('/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败')
      }
    },
    onSubmit () {
      // console.log('验证成功')
      this.doLogin()
    },
    onFailed () {
      console.log('验证失败')
    }

  }
}
</script>

<style lang="less" scoped>
// 按钮
.van-nav-bar {
  background-color: skyblue;
  .btn-wrap {
    padding: 30px;

    .van-button {
      width: 100%;
      background-color: #6db4fd;
      color: #fff;
    }
  }
}
</style>
